package swm.enterprise.rest.jdodemo.dao;

import java.util.List;

import javax.jdo.PersistenceManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Component;

import swm.enterprise.rest.jdodemo.model.Employee;
import swm.enterprise.rest.jdodemo.util.PMF;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class EmployeeDAOImpl implements EmployeeDAO {
	final Logger logger = LoggerFactory.getLogger(EmployeeDAOImpl.class);
	
	/* (non-Javadoc)
	 * @see swm.enterprise.rest.jdodemo.dao.EmployeeDAO#load(java.lang.String, java.lang.String)
	 */
	@Override
	public Employee load(String firstName, String lastName){
		PersistenceManager pm = null;
		Employee employee = null;
		try{
			pm = PMF.get().getPersistenceManager();
			Key key = KeyFactory.createKey(Employee.class.getSimpleName(),
					lastName + firstName);
			Employee retrieveEmp = pm.getObjectById(Employee.class, key);
			employee = pm.detachCopy(retrieveEmp);
		}catch (Exception e){
			System.out.println(e);
		}finally{
			pm.close();
		}
		return employee;
	}
	
	/* (non-Javadoc)
	 * @see swm.enterprise.rest.jdodemo.dao.EmployeeDAO#store(swm.enterprise.rest.jdodemo.model.Employee)
	 */
	@Override
	public void store(Employee employee){
		PersistenceManager pm = null;
		try{
			pm = PMF.get().getPersistenceManager();
			if(employee.getKey()==null){
				Key key = KeyFactory.createKey(Employee.class.getSimpleName(),
						employee.getLastName() + employee.getFirstName());
				employee.setKey(key);
			}
			pm.makePersistent(employee);
		}catch (Exception e){
			System.out.println(e);
		}finally{
			pm.close();
		}
	}
	
	/* (non-Javadoc)
	 * @see swm.enterprise.rest.jdodemo.dao.EmployeeDAO#delete(swm.enterprise.rest.jdodemo.model.Employee)
	 */
	@Override
	public void delete(Employee employee){
		PersistenceManager pm = null;
		try{
			pm = PMF.get().getPersistenceManager();
	        if (employee == null || employee.getKey() == null)
	        {
	            throw new RuntimeException("Employee is not persistent");
	        }else {
	        	Key key = KeyFactory.createKey(Employee.class.getSimpleName(),
						employee.getLastName() + employee.getFirstName());
				Employee e = pm.getObjectById(Employee.class, key);
	        	pm.deletePersistent(e);
	        }
		}catch (Exception e){
			System.out.println(e);
		}finally{
			pm.close();
		}
	}

	@Override
	public List<Employee> findAll() throws DataAccessException {
		// TODO Auto-generated method stub
		return null;
	}	
	
}
